


/**
 * User controller.
 */
class UsuarioController {

	def authenticateService
         CriptografiaDescriptografia cript  = new CriptografiaDescriptografia()
	// the delete, save and update actions only accept POST requests
	static Map allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

	def index = {
		redirect action: list, params: params
	}

	def list = {
		 
		[personList: Usuario.list(params)]
	}

	def show = {
		def person = Usuario.get(params.id)
		if (!person) {
			flash.message = "Usuario not found with id $params.id"
			redirect action: list
			return
		}
		List roleNames = []
		for (role in person.authorities) {
			roleNames << role.authority
		}
		roleNames.sort { n1, n2 ->
			n1 <=> n2
		}
		[person: person, roleNames: roleNames]
	}

	/**
	 * Person delete action. Before removing an existing person,
	 * he should be removed from those authorities which he is involved.
	 */
	def delete = {

		def person = Usuario.get(params.id)
		if (person) {
			def authPrincipal = authenticateService.principal()
			//avoid self-delete if the logged-in user is an admin
			if (!(authPrincipal instanceof String) && authPrincipal.username == person.username) {
				flash.message = "You can not delete yourself, please login as another admin and try again"
			}
			else {
				//first, delete this person from People_Authorities table.
				Permissao.findAll().each { it.removeFromPeople(person) }
				person.delete()
				flash.message = "Usuario $params.id deleted."
			}
		}
		else {
			flash.message = "Usuario not found with id $params.id"
		}

		redirect action: list
	}

	def edit = {

		def person = Usuario.get(params.id)
		if (!person) {
			flash.message = "Usuario not found with id $params.id"
			redirect action: list
			return
		}

		return buildPersonModel(person)
	}

	/**
	 * Person update action.
	 */
	def update = {

		def person = Usuario.get(params.id)
		 println params.passwd
                 println params.passwd

		def oldPassword = person.passwd
		person.properties = params
		if (!params.passwd.equals(oldPassword)) {
                 person.username = params.email
		 person.passwd = authenticateService.encodePassword(params.passwd)
                 person.pass =   person.passwd
		}
		person.username = params.email
                if (person.save()) {
			Permissao.findAll().each { it.removeFromPeople(person) }
			addRoles(person)

                       redirect action: show, id: person.id
		}
		else {
			render view: 'edit', model: buildPersonModel(person)
		}
	}

	  def create = {
        [person: new Usuario(params), authorityList: Permissao.findAll([sort:'authority',order:'asc'])]
    }

	/**
	 * Person save action.
	 */
	def save = {


		def person = new Usuario()
		 person.properties = params
                 person.username = params.email
		 person.passwd = authenticateService.encodePassword(params.passwd)
                 person.pass =   authenticateService.encodePassword(params.pass)
                 person.keyPass =   cript.criptografaLogin(params.pass)
		if (person.save()) {
			addRoles(person)
			redirect action: list
		}
		else {
			render view: 'create', model: [authorityList: Permissao.list(), person: person]
		}
	}


    def boot = {

        render "CRIADOS PERMISSÃO HOLE_ADMIN , HOLE_USUARIO <p> USUARIO MESTRE : aleste  , senha: 1104</p>"



    }


	private void addRoles(person) {
		for (String key in params.keySet()) {
			if (key.contains('ROLE') && 'on' == params.get(key)) {
				Permissao.findByAuthority(key).addToPeople(person)
			}
		}
	}

	private Map buildPersonModel(person) {

		List roles = Permissao.list()
		roles.sort { r1, r2 ->
			r1.authority <=> r2.authority
		}
		Set userRoleNames = []
		for (role in person.authorities) {
			userRoleNames << role.authority
		}
		LinkedHashMap<Permissao, Boolean> roleMap = [:]
		for (role in roles) {
			roleMap[(role)] = userRoleNames.contains(role.authority)
		}

		return [person: person, roleMap: roleMap]
	}



     def mudaSenha = {
        def login = authenticateService.principal()
        if (login.getUsername())  {
            def  usuario = Usuario.findByUsername(login.getUsername())
            def person = Usuario.get(usuario.id)
            if (person.userRealName == 'TEMP') {
                person.description=  ''
                person.email= ''
            }
            if (!person) {
                flash.message = "Usuario not found with id $params.id"
                redirect action: list
                return
            }

            return buildPersonModel(person) }

        else {
            render 'Erro Usuário Não Logado '
        }
    }
    def updatePass = {
        def person = Usuario.get(params.id)
         if (params.passwd != params.passwd2 || params.passwd == null || params.passwd == "" ) {
                flash.message = "As Senhas Não Coincidem"
                redirect action: mudaSenha, id: person.id
            } else {

            person.passwd = authenticateService.encodePassword(params.passwd)
            person.pass = authenticateService.encodePassword(params.passwd2)
	    person.email2 = person.email
               if (person.save()) {
                    flash.message = "Senha Alterada Com Sucesso!"
                    redirect uri: '/'
                    return
		}
		else {
                    
                    render view: 'mudaSenha', model: buildPersonModel(person)
		}

        }
 
               
            }
       


}
